<?php

namespace app\admin\controller;

use think\Controller;

class Passport extends Controller
{
    //登陆
    public function index()
    {
        if (session('user_data.id', '', 'account') && session('username', '', 'account')) {
            $this->redirect('index/index');
        }
        if (request()->isPost()) {
            $data = input('', null, 'htmlspecialchars');
            if (!captcha_check($data['captcha'])) {
                return json(array('code' => 0, 'msg' => '验证码错误'));
            }

            if (1) {
                session('username', "test", 'account');//登录用户名
                session('user_data', ["name" => "test", "id" => 3], 'account');//用户信息

                return json(['code' => 1, 'msg' => '登录成功!', 'url' => url('index/index')]);
            } else {
                return json(array('code' => 0, 'msg' => '用户名或者密码错误，重新输入!'));
            }
        }
        return $this->fetch();
    }

    /**
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    public function login($data)
    {
        $user = Admin::get(function ($query) use($data){
            $query->where('name', $data['username']);
            $query->cache(true, null, Admin::$cache_tag);
        });
        if (!empty($user)) {
            $login_data = array(
                'login_name' => $user['account'],
                'createtime' => $user['createtime'],
            );

            if ($user['password'] == encrypted_password($data['password'], $login_data)) {
                session('username', $user['name'], 'account');//登录用户名
                session('user_data', $user, 'account');//用户信息

                //用户是否是超级管理员
                if ($user['is_super'] == '1')
                    session('is_super', true, 'account');
                else
                    session('is_super', false, 'account');
                return true; //信息正确
            } else {
                return false; //密码错误
            }
        } else {
            return false; //用户不存在
        }
    }

    //退出登陆
    public function logout()
    {
        session(null, 'account');
        $this->redirect('passport/index');
    }

}
